<script setup>
// 个人信息页面 -- 这里的username要统一
import { reactive, ref, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { expiredLogin, takeAccessToken } from "@/api/login";
import router from "@/router";
import axios from 'axios';

onMounted(() => {
  // 获取用户信息
  getUserInfo()
})

async function getUserInfo() {
  try {
    const response = await axios.get('/api/auth/me', {
      headers: {
        'Authorization': `Bearer ${takeAccessToken()}`
      }
    });
    const data = response.data.data;

    // 更新 userInfo
    userInfo.value = Object.assign(userInfo, data)

    // 如果当前处于编辑状态，更新 editableUserInfo
    editableUserInfo.username = data.username;
    editableUserInfo.gender = data.gender;
    editableUserInfo.phone = data.phone;


  } catch (err) {
    console.log(err);
    // 可以添加错误处理逻辑，比如显示错误信息给用户等
  }
}

// 用户信息
const userInfo = reactive({});

// 是否编辑
const isEditing = ref(false);

// 可编辑的用户信息
const editableUserInfo = reactive({
  username: '',
  gender: '',
  phone: ''
});

// 性别选项
const genderOptions = ref([
  { value: 0, label: '男' },
  { value: 1, label: '女' }
]);

// 提交逻辑
const submitUserInfo = async () => {
  // console.log(userInfo)

  if (!isEditing.value) return; // 如果不是在编辑状态，直接返回

  try {
    await ElMessageBox.confirm('确认修改吗？', '警告信息', {
      confirmButtonText: '确认',
      cancelButtonText: '取消'
    }).then(action => {
      if(action === 'confirm'){
        // console.log(editableUserInfo.username)
        // 后端交互，提交数据
        axios.put('/api/auth/update-account', {
          username: editableUserInfo.username,
          gender: editableUserInfo.gender,
          phone: editableUserInfo.phone
        }, {
          headers: {
            'Authorization': `Bearer ${takeAccessToken()}`
          }
        })
        .then(() => {
          // console.log(res)
          isEditing.value = false; // 退出编辑状态
          getUserInfo()
        })
        .catch((err) => {
          console.log(err)
        })
      } else {
        return
      }
    })
  }
  catch (err){
    console.log(err)
  }

};

// ----------------------------------------------------------------------------------------------------------
// 修改密码

const formRef = ref();
const dialogFormVisible = ref(false);
const dialogVisible = ref(false); // 挂载图层默认不可见

const resetPasswordForm = reactive({
  newPassword: ''
})

const rules = {
  // oldPassword: [
  //   { required: true, message: '请输入旧密码', trigger: 'blur' },
  //   { validator: confirmOldPassword, trigger: 'blur' },
  // ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
    // { validator: confirmDiff, trigger: 'blur' },
  ],
  // confirmPassword: [
  //   { required: true, message: '请输入新密码', trigger: 'blur' }
  //  { validator: confirmPasswordValidator, trigger: 'change' },
  // ]
}

// // 判断旧密码是否正确
// function confirmOldPassword(rule, value, callback) {
//   // 从后端获取用户的登录密码
//   const password = '123456'
//   try{
//     if(value !== password) {
//       callback(new Error('旧密码错误！'));
//     } else {
//       callback();
//     }
//   } catch (err) {
//     console.log(err)
//   }
// }
// 判断旧密码和新密码是否一致
// function confirmDiff(rule, value, callback) {
//   try {
//     if (value === resetPasswordForm.oldPassword) {
//       callback(new Error('新密码不能与旧密码一致！'));
//     } else {
//       callback();
//     }
//   }catch (err){
//     console.log(err)
//   }
// }
// // 判断两次输入的新密码是否正确
// function confirmPasswordValidator(rule, value, callback) {
//   try {
//     if (value !== resetPasswordForm.newPassword) {
//       callback(new Error('两次输入的密码不一致！'));
//     } else {
//       callback();
//     }
//   }catch (err){
//     console.log(err)
//   }
// }

// 修改登录密码
function resetLoginPassword() {
  // console.log(resetPasswordForm.newPassword)
  // const id = userInfo.id
  formRef.value.validate((valid) => {
    try{
      if (valid) {
        ElMessageBox.confirm('确认修改吗？', '警告信息', {
          confirmButtonText: '确认',
          cancelButtonText: '取消'
        })
        .then(action => {
          if(action === 'confirm'){
            // 后端交互，提交数据
            axios.put('/api/auth/update-password',{
              // id: id,
              newPassword: resetPasswordForm.newPassword.toString()
            }, {
              headers: {
                'Authorization': `Bearer ${takeAccessToken()}`,
                "Content-Type": 'multipart/form-data'
              }
            })
            .then(() => {
              // console.log(res)
              ElMessage.success('修改密码成功')
              dialogVisible.value = true; // 显示对话框

              setTimeout(()=>{
                // 隐藏
                dialogFormVisible.value = false
                expiredLogin()
                router.push('/login')
              },2000)
            })
            .catch((err) => {
              console.log(err)
              ElMessage.warning('身份验证失败')
            })
          } else {
            return
          }
        })
        .catch((err) => {
          console.log(err)
        })
      }
      else {
        ElMessage.warning(`输入有误`)
        return false;
      }
    } catch (err){
      console.log(err)
    }
  });
}

// 重置个人密码
function resetPassword(){
  // console.log(userInfo.id)
  ElMessageBox.confirm('确认重置吗？', '警告信息', {
    confirmButtonText: '确认',
    cancelButtonText: '取消'
  }).then(action => {
    if(action === 'confirm'){
      axios.put('/api/auth/reset-password', {
        id: userInfo.id
      }, {
        headers: {
          'Authorization': `Bearer ${takeAccessToken()}`
        }
      })
      .then((res) => {
        ElMessage.success(res.data.data)
        // console.log(res)
        expiredLogin()
        ElMessage.warning('登录已过期，请重新登录')
        router.replace('/login')
      })
      .catch((err) => {
        console.log(err)
      })
    }
  })
  .catch((err) => {
    console.log(err)
  })

}

</script>

<template>
  <el-card>

    <!-- 查看个人信息 -->
    <div v-if="!isEditing">

      <el-descriptions :column="2" border>
        <el-descriptions-item label="账号">{{ userInfo.id }}</el-descriptions-item>
        <el-descriptions-item label="姓名">{{ userInfo.username }}</el-descriptions-item>
        <el-descriptions-item label="性别">{{ userInfo.gender === 0 ? '男' : userInfo.gender === 1 ? '女' : '未登记' }}</el-descriptions-item>
        <el-descriptions-item label="手机号码">{{ userInfo.phone }}</el-descriptions-item>
      </el-descriptions>

      <div class="buttonCss">
        <el-button type="primary" @click="isEditing = true" >编辑信息</el-button>
        <el-button type="primary" @click="dialogFormVisible = true">修改密码</el-button>
        <el-button type="primary" @click="resetPassword">重置密码</el-button>
      </div>

    </div>

    <!-- 修改个人信息 -->
    <el-form :model="editableUserInfo" ref="editForm" v-if="isEditing" label-width="100px">
      <el-form-item label="姓名" prop="username">
        <el-input v-model="editableUserInfo.username"></el-input>
      </el-form-item>
      <el-form-item label="性别" prop="gender">
        <el-select v-model="editableUserInfo.gender" placeholder="请选择性别">
          <el-option
              v-for="option in genderOptions"
              :key="option.value"
              :label="option.label"
              :value="option.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="手机号码" prop="phone">
        <el-input v-model="editableUserInfo.phone"></el-input>
      </el-form-item>

      <el-form-item class="buttonCss">
        <el-button type="primary" @click="submitUserInfo">保存</el-button>
        <el-button @click="isEditing = false">取消</el-button>
      </el-form-item>
    </el-form>

    <!-- 修改登录密码 -->
    <el-dialog title="修改登录密码" v-model="dialogFormVisible" style="margin-top: 188px;width: 40%;">
      <el-form :model="resetPasswordForm" ref="formRef" :rules="rules"  label-width="100px" style="margin: 18px 0;">
<!--        <el-form-item label="旧密码" prop="oldPassword">-->
<!--          <el-input v-model="resetPasswordForm.oldPassword" minlength="6" maxlength="20" autocomplete="off" placeholder="请输入旧密码"></el-input>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="新密码" prop="newPassword">-->
<!--          <el-input v-model="resetPasswordForm.newPassword" minlength="6" maxlength="20" autocomplete="off" placeholder="请输入新密码"></el-input>-->
<!--        </el-form-item>-->
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="resetPasswordForm.newPassword" minlength="6" maxlength="20" autocomplete="off" placeholder="请输入新密码"></el-input>
        </el-form-item>
      </el-form>

      <template v-slot:footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="resetLoginPassword">确 定</el-button>
        </div>
      </template>

    </el-dialog>

    <el-dialog
        v-model="dialogVisible"
        :modal="true"
        :fullscreen="true"
        :close-on-click-modal="false"
        :show-close="false"
        class="dialog">
      <span class="dialog-content">登录已过期，请重新登录</span>
    </el-dialog>

  </el-card>
</template>

<style scoped>
::v-deep .el-table__empty-text {
  font-size: 16px;
}
.buttonCss {
  margin-top: 18px;
}
.dialog{
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  background: rgba(0, 0, 0, 0.3); /* 背景半透明效果 */
  backdrop-filter: blur(10px); /* 毛玻璃效果 */
  z-index: 9999; /* 确保对话框在最顶层 */
}

.dialog-content{
  background-color: #fff; /* 白色背景 */
  border-radius: 4px; /* 圆角 */
  margin-top: 100px;
  padding: 20px; /* 内边距 */
  text-align: center; /* 文本居中 */
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  font-size: 28px;
}

</style>